package com.ws.service;

import com.github.pagehelper.PageHelper;
import com.ws.domain.Goods;
import com.ws.domain.Item;
import com.ws.domain.Order;
import com.ws.domain.User;
import com.ws.mapper.GoodsDao;
import com.ws.mapper.ItemMapper;
import com.ws.mapper.OrdersMapper;
import com.ws.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单
 */
@Service
public class OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询订单
     * @param status 订单状态
     * @param page 当前页
     * @param size 页大小
     * @return
     */
    public List<Order> pageOrder(Byte status,int page,int size){
        //开始分页
        PageHelper.startPage(page,size);
        //紧跟sql语句
        List<Order> orderByStatus = ordersMapper.findOrderByStatus(status);
        //查询每个订单的订单项和客户
        for (Order order : orderByStatus){
            //根据订单id查询订单的订单项，并设置进订单中
            List<Item> itemList = itemMapper.getItemsByOrderId(order.getId());
            //循环查询每一个订单项的商品详情
            for (Item item : itemList) {
                //根据商品id查询商品
                Goods good = goodsDao.getById(item.getGood_id());
                //将商品详情放入订单项中
                item.setGood(good);
            }
            //将订单项设置进订单中
            order.setItemList(itemList);
            //查询订单的客户，并设置进订单中
            User user = userMapper.getById(order.getUser_id());
            order.setUser(user);
        }
        return orderByStatus;
    }

    /**
     * 更新订单状态
     * @param id 订单ID
     * @param status 订单状态
     */
    public void orderUpdate(int id, byte status) {
        ordersMapper.orderUpdate(id,status);
    }

    /**
     * 删除订单
     * @param id 订单id
     */
    public void orderDelete(int id) {
        ordersMapper.orderDelete(id);
    }
}
